package cn.liuxue.lifecircle.bind;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

public class ActivityMessenger extends Activity {
	Messenger msg = null;
	boolean bound;
	
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			msg = new Messenger(service);
			bound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			msg = null;
			bound = false;
			
		}
		
	};

	public void sayHello() {
		Message message = Message.obtain(null, MessageService.MSG_SAY_HELLO, 0,0);
		try {
			msg.send(message);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		bindService(new Intent(this, MessageService.class), conn, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (bound) {
			unbindService(conn);
			bound = false;
		}
	}
	
	
	
}
